package com.note.common.interceptor;

import com.note.common.context.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 用户上下文拦截器
 * 从请求头中提取用户信息并设置到UserContext中
 */
@Slf4j
public class UserContextInterceptor implements HandlerInterceptor {

    /**
     * 用户ID在Header中的名称
     */
    private static final String HEADER_USER_ID = "X-User-Id";

    /**
     * 用户名在Header中的名称
     */
    private static final String HEADER_USERNAME = "X-Username";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String userIdStr = request.getHeader(HEADER_USER_ID);
        String username = request.getHeader(HEADER_USERNAME);

        // 只有当请求头中包含用户信息时才设置上下文
        if (StringUtils.hasText(userIdStr) && StringUtils.hasText(username)) {
            try {
                Long userId = Long.parseLong(userIdStr);
                UserContext.set(userId, username);
                
                log.debug("用户上下文已设置: userId={}, username={}, uri={}", 
                         userId, username, request.getRequestURI());
            } catch (NumberFormatException e) {
                log.warn("解析用户ID失败: value={}, uri={}", 
                        userIdStr, request.getRequestURI());
            }
        } else {
            log.debug("请求头中未找到用户信息: uri={}", request.getRequestURI());
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
                               Object handler, Exception ex) {
        // 请求处理结束后清理ThreadLocal，防止内存泄漏
        UserContext.clear();
        log.debug("用户上下文已清理: uri={}", request.getRequestURI());
    }
} 